package com.haoshuang.zhouzhoubang.ui.activity


import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore

import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityServiceLogBinding
import com.haoshuang.zhouzhoubang.model.bean.Image2Bean
import com.haoshuang.zhouzhoubang.ui.adapter.ImageAdapter23
import com.haoshuang.zhouzhoubang.ui.adapter.ServiceCaseImageAdapter
import com.haoshuang.zhouzhoubang.ui.vm.ServiceLogViewModel
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible


import java.io.FileNotFoundException
import java.io.IOException
import java.io.OutputStream


/**
 *
 */
class ServiceLogActivity : BaseVMActivity<ServiceLogViewModel, ActivityServiceLogBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.click { finish() }
        binding.appBar.tvTitle.text = "服务日志"
    }

    var list = arrayListOf<Image2Bean>()
    var list1 = arrayListOf<String>()
    var list2 = arrayListOf<Image2Bean>()
    var list3 = arrayListOf<Image2Bean>()
    var list21 = arrayListOf<String>()
    var list31 = arrayListOf<String>()
    var adapter: ImageAdapter23? = null
    var adapter2: ImageAdapter23? = null
    var adapter3: ImageAdapter23? = null
    var ids = 0
    var url1 = ""
    var url2 = ""
    var url3 = ""
    override fun initData() {


        ids = intent.getIntExtra("ids", 0)
        adapter = ImageAdapter23(list)
        adapter2 = ImageAdapter23(list2)
        adapter3 = ImageAdapter23(list3)
        adapter2?.setOnItemClickListener { adapter, view, position ->
            if (list2[position].isVideo == 0) {
                var list999 = arrayListOf<String>()
                list999.add(list2[position].image)
                startPage<LookActivity>("imgBeen" to list999, "position" to 0)
            } else {
                startPage<VideoActivity>("url" to list2[position].image)
            }

        }
        adapter3?.setOnItemClickListener { adapter, view, position ->
            if (list3[position].isVideo == 0) {
                var list999 = arrayListOf<String>()
                list999.add(list3[position].image)
                startPage<LookActivity>("imgBeen" to list999, "position" to position)
            } else {
                startPage<VideoActivity>("url" to list3[position].image)
            }

        }

        adapter?.setOnItemClickListener { adapter, view, position ->
            if (list[position].isVideo == 0) {
                var list999 = arrayListOf<String>()
                list999.add(list[position].image)
                startPage<LookActivity>("imgBeen" to list999, "position" to position)
            } else {
                startPage<VideoActivity>("url" to list[position].image)
            }
        }
        binding.apply {
            rvImage.layoutManager = GridLayoutManager(this@ServiceLogActivity, 4)
            rvImage2.layoutManager = GridLayoutManager(this@ServiceLogActivity, 4)
            rvImage3.layoutManager = GridLayoutManager(this@ServiceLogActivity, 4)
            rvImage.adapter = adapter
            rvImage2.adapter = adapter2
            rvImage3.adapter = adapter3
            tvShare.clickWithTrigger {
                startPage<ServiceLog3Activity>("ids" to ids)
            }
        }
        vm.getData("id" to ids)
        vm.getData2("id" to ids)

    }

    private fun setData(item: Map<String, Any>) {
        var avatar = item.get("avatar")
        var nickname = item.get("nickname")
        var service_score = item.get("service_score")
        var comment = item.get("comment")
        var pics = arrayListOf<String>()
        try {
            pics = item.get("pics") as ArrayList<String>
        } catch (e: Exception) {

        }

        var create_time = item.get("create_time")

        binding.apply {

            Glide.with(this@ServiceLogActivity)
                .load(avatar)
                .placeholder(R.mipmap.default_image)
                .error(R.mipmap.my_toux)
                .into(ivUserAvatar)
            textView36.text = nickname.toString()
            rbBar.rating = service_score.toString().toFloat()
            //  textView37.text = item.create_time
            tvName11.text = comment.toString()
            rvBeforeService.layoutManager =
                GridLayoutManager(this@ServiceLogActivity, 4)    // 给recycleview设置布局管理者
            val mrvBeforeAdapter = ServiceCaseImageAdapter(pics)
            rvBeforeService.adapter = mrvBeforeAdapter    // 给recycleview设置适配器对象
            mrvBeforeAdapter.setOnItemClickListener { adapter, view, position ->
                startPage<LookBigImgActivity>(
                    "imgBeen" to pics,
                    "position" to position
                )
            }

        }
    }

    fun getBitmap(view: NestedScrollView): Bitmap? {

        /*   var h = 0
           var bitmap: Bitmap? = null
           for (i in 0 until scrollView.getChildCount()) {
               h += scrollView.getChildAt(i).getHeight()
               scrollView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"))
           }
           bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565)
           val canvas = Canvas(bitmap)
           scrollView.draw(canvas)*/

        var h = 0

        // 获取listView实际高度
        for (i in 0 until view.getChildCount()) {
            h += view.getChildAt(i).getHeight()
            view.getChildAt(i).setBackgroundResource(R.color.white)
        }

        // 创建对应大小的bitmap
        var bitmap = Bitmap.createBitmap(
            view.getWidth(), h,
            Bitmap.Config.RGB_565
        )
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        /*  val width = view.width
          val height = view.height
          val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
          val canvas = Canvas(bitmap)
          view.draw(canvas)*/
        return bitmap
    }

    var type9 = 2
    fun addBitmapToAlbum(
        context: Context,
        bitmap: Bitmap
    ) {
        val displayName = "111jpg"
        val mimeType = "image/jpeg"
        val compressFormat = Bitmap.CompressFormat.JPEG

        val values = ContentValues()
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
        } /*else {
            values.put(
                MediaStore.MediaColumns.DATA,
                Environment.getExternalStorageDirectory().path + Environment.DIRECTORY_DCIM + displayName
            )
        }*/
        val contentResolver = context.contentResolver
        val uri: Uri? = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        //ToastUtils.show("保存成功 ")
        if (uri != null) {
            var outputStream: OutputStream? = null
            try {
                outputStream = contentResolver.openOutputStream(uri)
                bitmap.compress(compressFormat, 100, outputStream)
                outputStream?.close()
                try {
                    when (type9) {

                        2 -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                var phth = getFileUri(context, uri)
                                PaymentUtil.wxShareALl2(context, bitmap, false, phth)
                            } else {
                                PaymentUtil.wxShareALl2(
                                    context,
                                    bitmap,
                                    false,
                                    uri.path
                                )
                            }

                        }

                        3 -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                var phth = getFileUri(context, uri)
                                PaymentUtil.wxShareALl2(context, bitmap, true, phth)
                            } else {
                                PaymentUtil.wxShareALl2(
                                    context,
                                    bitmap,
                                    true,
                                    uri.path
                                )
                            }


                        }
                    }

                } catch (e: Exception) {

                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            if (outputStream != null) {
            }
        }
    }

    fun getFileUri(context: Context, contentUri: Uri): String? {
        // 授权给微信访问路径
        context.grantUriPermission(
            "com.tencent.mm",  // 这里填微信包名
            contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
        return contentUri.toString() // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }

    override fun startObserve() {
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    binding.apply {
                        ivHead.load(it.image, R.mipmap.rl)
                        tvName.text = it.store_name
                        tvMaij.text = it.suk_unique
                        tvOrderSn.text = "订单编号:" + it.order_id
                    }
                }
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    list.clear()
                    list1.clear()
                    list2.clear()
                    list21.clear()
                    if (!it.before_service_img.isNullOrBlank()) {
                        var arr = it.before_service_img.split(",")
                        list1.addAll(arr)
                        for (b in arr) {
                            list.add(Image2Bean(b, 0))
                            list1.add(b)
                        }

                    }
                    if (!it.before_service_video.isNullOrBlank()) {
                        list.add(Image2Bean(it.before_service_video, 1))
                        url1 = it.before_service_video
                    }
                    if (!it.service_img.isNullOrBlank()) {
                        var arr = it.service_img.split(",")
                        list21.addAll(arr)
                        for (b in arr) {
                            list2.add(Image2Bean(b, 0))
                        }

                    }
                    if (!it.service_video.isNullOrBlank()) {
                        list2.add(Image2Bean(it.service_video, 1))
                        url2 = it.service_video
                    }
                    if (!it.after_service_img.isNullOrBlank()) {
                        var arr = it.after_service_img.split(",")
                        list31.addAll(arr)
                        for (b in arr) {
                            list3.add(Image2Bean(b, 0))
                        }

                    }
                    if (!it.after_service_video.isNullOrBlank()) {
                        list3.add(Image2Bean(it.after_service_video, 1))
                        url3 = it.after_service_video
                    }
                    adapter?.notifyDataSetChanged()
                    adapter2?.notifyDataSetChanged()
                    adapter3?.notifyDataSetChanged()
                    try {
                        var str = it.store_product_reply as Map<String, Any>


                        setData(str)
                        binding.llRz.visible()
                    } catch (e: Exception) {
                        binding.llRz.gone()
                    }

                }
            }
        }
    }

}